from django.shortcuts import render
from rest_framework.response import Response
from home import models,homeser
from rest_framework.views import APIView
from django.core.cache import cache
# Create your views here.
class HomeNav(APIView):
    def get(self,request):
        # 首先设置该接口的缓存key
        key="headnav"
        # 去缓存中读取数据
        navlist=cache.get(key)
        if navlist:
            return Response({"code":200,"mag":"ok","data":navlist})
        navlist=models.Nav.objects.filter(position=0,flag=True).order_by("order")
        ser=homeser.NavSerializer(navlist,many=True)
        # 将数据添加到缓存中
        cache.set(key,ser.data,60*60*24)
        return Response({"code":200,"msg":"ok","data":ser.data})

class FooNav(APIView):
    def get(self,request):
        navlist=models.Nav.objects.filter(position=1,flag=False).order_by("order")
        ser=homeser.NavSerializer(navlist,many=True)
        return Response({"code":200,"msg":"ok","data":ser.data})

class Banner(APIView):
    def get(self,request):
        bannerlist=models.Banner.objects.filter(flag=True).order_by("order")
        ser=homeser.BannerSerializer(bannerlist,many=True)
        return Response({"code":200,"msg":"ok","data":ser.data})
from rest_framework.generics import ListAPIView
class BannerList(ListAPIView):
    queryset = models.Banner.objects.filter(flag=True).order_by("order")
    serializer_class = homeser.BannerSerializer

#文件上传的接口
from django.core.files.storage import default_storage
class UploadFile(APIView):
    def post(self,request):
        file=request.data.get("file")
        types=['jpg','png','jpeg']
        if file.name.split(".")[-1] not in types:
            return Response({"code":201,"msg":"上传的文件类型不对"})
        if file.size > 2*1024*1024:
            return Response({"code":201,"msg":"上传的文件过大"})
        uploadfile=default_storage.save("banner/"+file.name,file)
        url=default_storage.url(uploadfile)
        return Response({"url":url})